package com.cloud.controller;

import cn.hutool.script.ScriptUtil;
import com.cloud.config.ScriptEnginePool;
import com.cloud.model.entity.HwItem;
import com.cloud.model.entity.User;
import com.cloud.model.req.ExecuteRuleReq;
import com.cloud.utils.RuleUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/BydRule")
@RestController
public class BydRuleController {
    @Autowired
    private ScriptEnginePool scriptEnginePool;

    @PostMapping("/executeBydRule")
    public Boolean executeBydRule(@RequestBody List<ExecuteRuleReq> executeRuleReqList) throws ScriptException, InterruptedException {
//        ScriptEngineManager manager = new ScriptEngineManager();
//        ScriptEngine engine = manager.getEngineByName("python");
        ScriptEngine scriptEngine = scriptEnginePool.acquireEngine();
        User user = new User();
        user.setAge("20");
        user.setName("张三");
        List<String> arrayList = new ArrayList<>();
        arrayList.add("01-家用空调");
        arrayList.add("02-滚筒洗衣机");
        arrayList.add("00-通用类");
        user.setDeptList(arrayList);

        HwItem hwItem = new HwItem();
        hwItem.setPartNumber("001070482");
        hwItem.setOwnerId("张三");
        hwItem.setHrBUNo("00-通用类");
        hwItem.setLifeCycleState("LcsWorking");
        scriptEngine.put("user", user);
        scriptEngine.put("businessObj", hwItem);
        for (ExecuteRuleReq executeRuleReq : executeRuleReqList) {
            String expression = executeRuleReq.getExpression();
            Map<String, String> variables = new HashMap<>();
            String replaceExpressionByString = RuleUtils.getReplaceExpressionByString(expression, variables);
            for (Map.Entry<String, String> entry : variables.entrySet()) {
                scriptEngine.put(entry.getKey(), entry.getValue());
            }
            Thread.sleep(999999);
            Boolean eval = (Boolean) scriptEngine.eval(replaceExpressionByString);
            System.out.println(eval);
//            if (!eval){
//                return false;
//            }

        }
        return true;
    }

    @PostMapping("/test")
    public Boolean test() {

        System.out.println(scriptEnginePool.acquireEngine());
        return true;
    }

}
